package com.ErpCoreWeb.View;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ErpCoreModel.Base.CUser;
import com.ErpCoreModel.Framework.CBaseObject;
import com.ErpCoreModel.Framework.CColumn;
import com.ErpCoreModel.Framework.CTable;
import com.ErpCoreModel.Framework.Util;
import com.ErpCoreModel.UI.CView;
import com.ErpCoreModel.UI.CViewFilter;
import com.ErpCoreModel.UI.CViewFilterMgr;
import com.ErpCoreWeb.Common.Global;

/**
 * Servlet implementation class SetViewFilter
 */
@WebServlet("/SetViewFilter")
public class SetViewFilter extends HttpServlet {
	private static final long serialVersionUID = 1L;

	HttpServletRequest request;
	HttpServletResponse response;

    public CUser m_User = null;
    public CTable m_Table = null;
    public CView m_View = null;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SetViewFilter() {
        super();
        // TODO Auto-generated constructor stub
    }

    //初始化变量
    void initData()
    {
        if (request.getSession().getAttribute("User") == null)
        {
            try {
				response.sendRedirect("../Login.jsp");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return ;
        }
		try {
			m_User = (CUser) request.getSession().getAttribute("User");

			String vid = request.getParameter("vid");
			if (Global.IsNullParameter(vid)) {
				response.getWriter().close();
			}
			m_View = (CView) Global.GetCtx(this.getServletContext())
					.getViewMgr().Find(Util.GetUUID(vid));
			if (m_View == null) {
				response.getWriter().close();
			}
			m_Table = (CTable) Global.GetCtx(this.getServletContext())
					.getTableMgr().Find(m_View.getFW_Table_id());

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}
	void doProc(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{

		this.request=request;
		this.response=response;

		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");

		//初始化变量
	    initData();
	    //
        String Action = request.getParameter("Action");
        if (Action == null) Action = "";

        if (Action.equalsIgnoreCase("GetData"))
        {
        	GetData();
            return ;
        }
        else if (Action.equalsIgnoreCase("Delete"))
        {
        	Delete();
            return ;
        }
        else if (Action.equalsIgnoreCase("Add"))
        {
        	Add();
            return ;
        }
	}

    void GetData()
    {
        String sData = "";
        int iCount = 0;

        if (request.getSession().getAttribute("ViewFilterMgr") != null)
        {
            Map<UUID, CViewFilterMgr> sortObj = (Map<UUID, CViewFilterMgr>)request.getSession().getAttribute("ViewFilterMgr");
            if (sortObj.containsKey(m_View.getId()))
            {
                CViewFilterMgr ViewFilterMgr = sortObj.get(m_View.getId());
                ViewFilterMgr.setIsLoad ( true); //避免从数据库装载
                List<CBaseObject> lstObj = ViewFilterMgr.GetList();
                for (CBaseObject obj : lstObj)
                {
                    CViewFilter ViewFilter = (CViewFilter)obj;

                    CColumn col = (CColumn)m_Table.getColumnMgr().Find(ViewFilter.getFW_Column_id());
                    if (col == null)
                        continue;

                    sData += String.format("{ \"id\": \"%s\",\"AndOr\":\"%s\",\"Column\":\"%s\",\"Sign\":\"%s\", \"Val\":\"%s\" },"
                        , ViewFilter.getId().toString()
                        , ViewFilter.getAndOr().equalsIgnoreCase("and") ? "与" : "或"
                        , col.getName()
                        , ViewFilter.GetSignName()
                        , ViewFilter.getVal());

                    iCount++;
                }
            }
        }
		if (sData.endsWith(","))
			sData = sData.substring(0, sData.length() - 1);
        sData = "[" + sData + "]";
        String sJson = String.format("{\"Rows\":{0},\"Total\":\"{1}\"}"
            , sData, iCount);

        try {
			response.getWriter().print(sJson);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    void Delete()
    {
        String delid = request.getParameter("delid");
        if (Global.IsNullParameter(delid))
        {
        	try {
				response.getWriter().print("请选择一项！");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return;
        }
        
        
        if (request.getSession().getAttribute("ViewFilterMgr") == null)
            return;
        Map<UUID, CViewFilterMgr> sortObj = (Map<UUID, CViewFilterMgr>)request.getSession().getAttribute("ViewFilterMgr");
        if (sortObj.containsKey(m_View.getId()))
        {
            CViewFilterMgr ViewFilterMgr = sortObj.get(m_View.getId());

            ViewFilterMgr.Delete(Util.GetUUID(delid));
        }
    }
   

    void Add()
    {
		String txtVal = request.getParameter("txtVal");
		String cbAndOr = request.getParameter("cbAndOr");
		String cbColumn = request.getParameter("cbColumn");
		String cbSign = request.getParameter("cbSign");
		
        if (request.getSession().getAttribute("ViewFilterMgr") == null)
        {
        	Map<UUID, CViewFilterMgr> sortObj0 = new HashMap<UUID,CViewFilterMgr>();
            CViewFilterMgr ViewFilterMgr0 = new CViewFilterMgr();
            ViewFilterMgr0.Ctx = Global.GetCtx(this.getServletContext());
            sortObj0.put(m_View.getId(),ViewFilterMgr0);
            request.getSession().setAttribute("ViewFilterMgr", sortObj0);
        }
        Map<UUID, CViewFilterMgr> sortObj = (Map<UUID, CViewFilterMgr>)request.getSession().getAttribute("ViewFilterMgr");
        if (!sortObj.containsKey(m_View.getId()))
        {
            CViewFilterMgr ViewFilterMgr0 = new CViewFilterMgr();
            ViewFilterMgr0.Ctx = Global.GetCtx(this.getServletContext());
            sortObj.put(m_View.getId(), ViewFilterMgr0);
        }
        CViewFilterMgr ViewFilterMgr = sortObj.get(m_View.getId());

        
        CViewFilter Filter = new CViewFilter();
        Filter.Ctx = Global.GetCtx(this.getServletContext());
        Filter.setUI_View_id ( m_View.getId());
        Filter.setAndOr ( cbAndOr);
        Filter.setFW_Table_id ( m_Table.getId());
        Filter.setFW_Column_id (Util.GetUUID(cbColumn));
        if(cbSign.equals(">"))
        	Filter.setSign (0);
        else if(cbSign.equals("<"))
        	Filter.setSign (1);
        else if(cbSign.equals(">="))
        	Filter.setSign (2);
        else if(cbSign.equals("<="))
        	Filter.setSign (3);
        else if(cbSign.equals("!="))
        	Filter.setSign (4);
        else if(cbSign.equals("like"))
        	Filter.setSign (5);
        Filter.setVal ( txtVal);
        Filter.setIdx ( m_View.getViewFilterMgr().GetList().size());

        ViewFilterMgr.AddNew(Filter);
    }

}
